import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.util.*;
import javax.media.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import javax.media.rtp.rtcp.*;
import javax.media.protocol.*;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.Format;
import javax.media.format.FormatChangeEvent;
import javax.media.control.BufferControl;
import com.sun.media.rtp.RTPSessionMgr;
import javax.swing.*;
import javax.swing.event.*;



public class ReceiverAV extends Komunikator implements SessionListener, ReceiveStreamListener, RemoteListener  {
	RTPManager rtpmanager;
	String loc_video_port_srv;
	String loc_audio_port_srv;
	String transmision_type=null;
	DataSource ds;
	String sz_imie;
	New_Cam nw = null; 
	static String adr_ip;

	
public ReceiverAV(String p_s_v,String p_s_a){
	loc_video_port_srv=p_s_v;
	loc_audio_port_srv=p_s_a;
	System.out.println("Uruchamiam serwer nasluchu polaczenia");
}

public void create_Video_srv(String ip,String cl_port) throws InvalidSessionAddressException, IOException{
	
	String _port=loc_video_port_srv;   //lokalny port na jakim dziala server 
	InetAddress ipAddr = null;
	SessionAddress local_adress = null;
	SessionAddress dest_adress;
	
	
	rtpmanager = RTPManager.newInstance();
	rtpmanager.addSessionListener(this);
	rtpmanager.addReceiveStreamListener(this);
	rtpmanager.addRemoteListener(this);
	
	//tworzenie IP wysylajacego
	ipAddr = InetAddress.getByName(ip);
	int local_PORT = new Integer(cl_port).intValue();
	// tworzenie lokalnego adresu 
	local_adress = new SessionAddress(InetAddress.getLocalHost(),local_PORT);
	//	tworzenie adresu z ktorego nasluchujemy
	int dest_port = new Integer(_port).intValue();
	dest_adress = new SessionAddress(ipAddr,dest_port);


	rtpmanager.initialize(local_adress);
	
        BufferControl bc = (BufferControl)rtpmanager.getControl("javax.media.control.BufferControl");
	if (bc != null)
        bc.setBufferLength(350);

        //Tutaj byc moze buffer control


	rtpmanager.addTarget(dest_adress);
	
	
}


public void create_Audio_srv(String ip,String cl_port) throws InvalidSessionAddressException, IOException{
	
	String _port=loc_audio_port_srv;   //lokalny port na jakim dziala server 
	InetAddress ipAddr = null;
	SessionAddress local_adress = null;
	SessionAddress dest_adress;
	
	rtpmanager = RTPManager.newInstance();
	rtpmanager.addSessionListener(this);
	rtpmanager.addReceiveStreamListener(this);
	rtpmanager.addRemoteListener(this);
	
	//tworzenie IP wysylajacego
	ipAddr = InetAddress.getByName(ip);
	int local_PORT = new Integer(cl_port).intValue();
	// tworzenie lokalnego adresu 
	local_adress = new SessionAddress(InetAddress.getLocalHost(),local_PORT);
	//	tworzenie adresu z ktorego nasluchujemy
	int dest_port = new Integer(_port).intValue();
	dest_adress = new SessionAddress(ipAddr,dest_port);


	rtpmanager.initialize(local_adress);
	//Tutaj byc moze buffer control 
	rtpmanager.addTarget(dest_adress);
	
}

public String get_Transmision_Type(){
	return transmision_type;
}

	public void update(ReceiveStreamEvent arg0) {
		//addreceivstram lister
		RTPManager mgr = (RTPManager)arg0.getSource();
		Participant participant = arg0.getParticipant();	// could be null.
		ReceiveStream stream = arg0.getReceiveStream();  // could be null.
		String c_name=null;
		
		
//		Proba pobrania CNAME, jesli poprzednia sie nie powiodla
		if (arg0 instanceof StreamMappedEvent) {
			{
				
		
			System.err.println("had now been identified as sent by: " + participant.getCNAME());
		    c_name=participant.getCNAME();
			}	
		
	   //Identyfikacja adresu IP przychodzacego polaczenia
	
		String n_hosta = c_name.substring(c_name.indexOf("@")+1,c_name.length());
		
                InetAddress[] ipek=null;
		try {
			ipek = InetAddress.getAllByName(n_hosta);

		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	 
			
		adr_ip=ipek[0].getHostAddress();
		}
		
	
		if (arg0 instanceof NewReceiveStreamEvent){
		//Tworzenie Data Source
		stream = ((NewReceiveStreamEvent)arg0).getReceiveStream();
		ds = stream.getDataSource();
		//Sprawdzanie formatu
		RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
		System.err.println("  - Recevied new RTP stream: " + ctl.getFormat().toString());
		System.out.println(ctl.getFormat().toString().length());
		
	
	
		//Do zmiany !!!!!
		if (ctl.getFormat().toString().length()==31){
			System.out.println("Wybralem Audio");
			transmision_type="audio";}
		else {
			transmision_type="video";
		System.out.println("Wybralem Video");
		}

		//Tworzenie nowego okna z playerem dla przychodzacego polaczenia
		try {
			nw = new New_Cam(ds,transmision_type,super.gCloseAllButton,adr_ip);
			nw.setVisible(true);
		} catch (CannotRealizeException ev) {
			// TODO Auto-generated catch block
                        ev.printStackTrace();
                        

		}
		
		//IncomFrame InFrame = new IncomFrame();
		//InFrame.setVisible(true);



		
	
		}
			
	}

	public void update(SessionEvent arg0) {
		
		//addSesionListener
		if (arg0 instanceof NewParticipantEvent) {
		    Participant p = ((NewParticipantEvent)arg0).getParticipant();
		    System.out.println(p.getReports());
		    System.out.println("-------------------");
		    System.err.println("  - A new participant had just joined: " + p.getCNAME());
		    
		    
		    
		
		    
		}
		
		
		
	}

	public void controllerUpdate(ControllerEvent arg0) {
		
		
	}
	

	public void update(RemoteEvent arg0) {
		System.out.println("Trwa transmisja");
		
	}
	
		

	
class  IncomFrame extends JFrame{

public IncomFrame() {
        setResizable(false);
        setSize(250,150);
        JLabel label = new JLabel("Czy odebrac polaczenie od "+sz_imie);
        JButton buttonYes = new JButton(new ImageIcon("icon/phoneZ.png"));
        JButton buttonNo = new JButton(new ImageIcon("icon/phone.png"));
        
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(buttonYes);
        buttonPanel.add(buttonNo);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        getContentPane().add(label,BorderLayout.NORTH);

        buttonYes.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        System.out.println("odebralem");



        }
        });
        
        buttonNo.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        System.out.println("nie odebralem");
        }
        });
 }


}
}

/*
 * Przyklad uzycia klasy
	//sypie sie gdy nie jest wykonwyane w watku (niekiedy) - problem ze stanami odtwarzacza !!!
	ReceiverAV tr = new ReceiverAV("4226","4228");
	tr.create_Video_srv("192.168.1.2","4444");
	tr.create_Audio_srv("192.168.1.2","4448");
	
*/
